<?php

namespace App\Http\Controllers\Admin;

use App\Models\Node;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class NodeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //获取所有节点
        $data = (new Node)->getAllList();
        return view('admin.node.index',compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     * 
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
		//获取父节点
		$data = Node::where('pid',0)->get();
        return view('admin.node.create',compact('data'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		//表单验证
		try{
			$this->validate($request,[
				'name' => 'required|unique:nodes,name',
			]);
		}catch(\Exception $e){
			return ['status' => 1000 , 'msg' => '验证不通过'];
		}
		//全部验证之后进行入库操作
		Node::create($request->except('_token'));
        return ['status' => 0 , 'msg' => 'success'];
    }

    /**
     * Display the specified resource.
     * 
     * @param  \App\Models\Node  $node
     * @return \Illuminate\Http\Response
     */
    public function show(Node $node)
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Node  $node
     * @return \Illuminate\Http\Response
     */
    public function edit(int $id)
    {
		//查找当前节点的信息
		$find = Node::find($id);
		//获取所有节点
		$data = (new Node)->getAllList();
        return view('admin.node.edit',compact('data','find'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Node  $node
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, int $id)
    {
        try{
          $this->validate($request,[
            'name' => 'required'
          ]);
        }catch(\Exception $e){
          return ['status' => 1000,'msg'=>'验证不通过'];
        }
        //修改数据
        Node::where(['id'=>$id])->update($request->except(['_token','_method']));
        return ['status' => 0 ,'msg' => '修改成功'];
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Node  $node
     * @return \Illuminate\Http\Response
     */
    public function destroy(int $id)
    {
		//这里使用的是软删除
		Node::find($id)->delete();
		return ['status' => 0,'msg' => '删除成功'];
    }
}
